package com.hopedove.callsystem.activity.call;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hopedove.base.BaseActivity;
import com.hopedove.callsystem.R;
import com.hopedove.callsystem.constant.ConstantsKt;
import com.hopedove.callsystem.databinding.ActivityCallMaterialInfoBinding;
import com.hopedove.callsystem.domain.net.CallMaterialInfo;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.TipsDialogFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


@SuppressLint({"NewApi", "HandlerLeak"})
public class ConfirmInfoActivity extends BaseActivity implements OnClickListener {

    private static JSONArray jsonArray; // 列表数据源
    private TipsDialogFragment tipDialog;
    private final HashMap<String, String> numberMap = new HashMap<>(); // 存储列表中的Edit值
    private ActivityCallMaterialInfoBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCallMaterialInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Intent intent = getIntent();
        try {
            jsonArray = new JSONArray(intent.getStringExtra(ScanBarcodeActivity.SOURCE_DATA));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String ticketNo = intent.getStringExtra(ConstantsKt.getTICKET_NO());
        binding.title.setText("布票号 ：" + ticketNo);
        binding.titleNum.setText("呼叫个数 ：" + jsonArray.length() + "  ");
        binding.infoListview.setAdapter(new MyListAdapter());

        binding.callImg.setImageResource(R.drawable.confirmcallbtnxml);
        binding.callImg.setOnClickListener(this);
        binding.backImg.setOnClickListener(this);
    }


    /**
     * 自定义adapter
     */
    class MyListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private Integer index = -1;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            String materialName = null;
            String materialNumber = null;

            try {
                JSONObject jsonObject = jsonArray.getJSONObject(position);
                materialName = jsonObject.getString(ConstantsKt.getMATERIAL_NAME());
                materialNumber = jsonObject.getString(ConstantsKt.getMATERIAL_NUMBER());
                if (materialNumber.equals("null"))
                    materialNumber = "";
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ViewHolder viewHolder = null;
            if (convertView == null) {

                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.list_item1, null);
                viewHolder.info_tv = convertView.findViewById(R.id.info_tv);
                viewHolder.num_tv = convertView.findViewById(R.id.num_tv);
                viewHolder.num_tv.setTag(position);
                viewHolder.num_tv.setOnTouchListener((v, event) -> {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        index = (Integer) v.getTag();
                    }
                    return false;
                });

                class MyTextWatcher implements TextWatcher {
                    public MyTextWatcher(ViewHolder holder) {
                        mHolder = holder;
                    }

                    private ViewHolder mHolder;
                    private int editEnd;
                    private CharSequence temp;

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        temp = s;
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        // 控制输入框只能接受5为数字，超过5位后，自动覆盖
                        editEnd = mHolder.num_tv.getSelectionEnd();
                        if (temp.length() > 5) {
                            s.delete(0, editEnd - 1);
                            mHolder.num_tv.setText(s);
                            mHolder.num_tv.setSelection(editEnd + 1);
                        }
                        // 当EditText数据发生改变的时候存到NumberMap变量中
                        if (s != null && !"".equals(s.toString())) {
                            int position = (Integer) mHolder.num_tv.getTag();
                            numberMap.put(String.valueOf(position), s.toString());
                        }
                    }

                }

                viewHolder.num_tv.addTextChangedListener(new MyTextWatcher(viewHolder));
                convertView.setTag(viewHolder);
            } else {

                viewHolder = (ViewHolder) convertView.getTag();
                viewHolder.num_tv.setTag(position);
            }

            viewHolder.info_tv.setText(materialName);

            if (numberMap.get(String.valueOf(position)) != null && !"".equals(numberMap.get(String.valueOf(position)))) {
                viewHolder.num_tv.setText(numberMap.get(String.valueOf(position)));
            } else {
                viewHolder.num_tv.setText(materialNumber);
            }
            viewHolder.num_tv.clearFocus();
            if (index != -1 && index == position) {
                viewHolder.num_tv.requestFocus();
            }


            return convertView;
        }

        public class ViewHolder {
            private TextView info_tv;
            private EditText num_tv;
        }

    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.call_img) {

            if (numberMap.size() != jsonArray.length()) {
                Toast.makeText(this, "未输入只数,无法确认", Toast.LENGTH_SHORT).show();
                return;
            }
            View dialogContent = getLayoutInflater().inflate(R.layout.loading, null);
            TextView textView = dialogContent.findViewById(R.id.tip);
            String tipStr = "提交呼叫中...";
            textView.setText(tipStr);
            tipDialog = TipsDialogFragment.showNewInstance(this, dialogContent, false);
            call();
        } else if (v.getId() == R.id.back_img) {
            finish();
        }
    }


    /**
     * 进行呼叫
     */
    void call() {

        try {
            JSONArray array = new JSONArray();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                JSONObject item = new JSONObject();
                item.put(ConstantsKt.getTASK_NO(), json.getString(ConstantsKt.getTASK_NO()));
                item.put(ConstantsKt.getMATERIAL_ID(), json.getString(ConstantsKt.getMATERIAL_ID()));
                item.put(ConstantsKt.getMATERIAL_YLLX(), json.getString(ConstantsKt.getMATERIAL_YLLX()));
                item.put(ConstantsKt.getMATERIAL_NUMBER(), numberMap.get(String.valueOf(i)));
                array.put(item);
            }

            Communication.asyncRequest(new CallMaterialInfo(array.toString()), r -> {
                TipsDialogFragment.dismissTipDialog(tipDialog);

                if (r instanceof OkResponse) {
                    tipDialog = TipsDialogFragment.showNewInstance(this, R.layout.callsys_tips_type_2, false);
                    uiHandler.postDelayed(() -> {
                        TipsDialogFragment.dismissTipDialog(tipDialog);
                        Intent intent = new Intent(this, CallMainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }, 3000);

                } else if (r instanceof ErrResponse) {
                    ToastUtil.longToast(getBaseContext(), ((ErrResponse) r).getErrText());
                }
            });

        } catch (JSONException e) {
            ToastUtil.longToast(getBaseContext(), "呼叫失败，请重新选择");
        }

    }

}
